// db.ts
const DB_NAME = 'testDB';
const DB_VERSION = 1;
const storeName = 'user';

// 连接数据库
function openDB() {
    return new Promise((resolve, reject) => {
        const request = indexedDB.open(DB_NAME, DB_VERSION);

        request.onupgradeneeded = (event: IDBVersionChangeEvent) => {
            const db = event.target.result as IDBDatabase;
            if (!db.objectStoreNames.contains(storeName)) {
                db.createObjectStore(storeName, { keyPath: 'id', autoIncrement: true });
            }
        };

        request.onsuccess = (event: Event) => {
            resolve(event.target.result as IDBDatabase);
        };

        request.onerror = (event: Event) => {
            reject(event.target.error);
        };
    });
}

// 添加用户
export function addUser(userName: string, sex: string, age: number): Promise<void> {
    return new Promise((resolve, reject) => {
        openDB().then((db) => {
            const transaction = db.transaction([storeName], 'readwrite');
            const store = transaction.objectStore(storeName);
            const request = store.add({ userName, sex, age });

            transaction.oncomplete = () => {
                db.close();
                resolve();
            };

            transaction.onerror = () => {
                db.close();
                reject(transaction.error);
            };

            request.onerror = () => {
                reject(request.error);
            };
        }).catch(reject);
    });
}

// 获取用户列表
export function getUserList(): Promise<any[]> {
    return new Promise((resolve, reject) => {
        openDB().then((db) => {
            const transaction = db.transaction([storeName]);
            const store = transaction.objectStore(storeName);
            const request = store.getAll();

            request.onsuccess = () => {
                db.close();
                resolve(request.result);
            };

            request.onerror = () => {
                db.close();
                reject(request.error);
            };
        }).catch(reject);
    });
}

// 删除用户
export function delUser(id: number): Promise<void> {
    return new Promise((resolve, reject) => {
        openDB().then((db) => {
            const transaction = db.transaction([storeName], 'readwrite');
            const store = transaction.objectStore(storeName);
            const request = store.delete(id);

            transaction.oncomplete = () => {
                db.close();
                resolve();
            };

            transaction.onerror = () => {
                db.close();
                reject(transaction.error);
            };

            request.onerror = () => {
                reject(request.error);
            };
        }).catch(reject);
    });
}